package com.eazy.lkv2.core.util;

import com.eazy.lkv2.core.Global;
import com.eazy.lkv2.core.web.utils.MD5;
import com.eazy.lkv2.web.vo.ActivityPoster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class PostMaker {
    private static Logger log = LoggerFactory.getLogger(PostMaker.class);


    public static void main(String[] args) {
        String dir="./src/main/webapp/xiu/";
        String bg = dir+"poster_bg.jpg";
        List<ImgBean> imgBeans = new ArrayList<>();
        List<TextBean> textBeans = new ArrayList<>();
        int offset=0;
        imgBeans.add(imgParameter(imgLoadUrl(dir+"test_poster.jpg"), false, 0, offset, 1080, 750));
        imgBeans.add(imgParameter(imgLoadUrl(dir+"qrcode.jpg"), false, 720, 1530, 300, 300));
         offset=900;
        String title="宁波老板娘新光大国际酒店会议厅";
        textBeans.add(textParameter(title, false, 1.0f,70, offset, Color.BLACK,new Font(null,Font.BOLD,72)));
//        offset+=102;
//        textBeans.add(textParameter("议厅", false, 1.0f,70, offset, Color.BLACK,new Font(null,Font.BOLD,72)));
        offset+=200;
        if(title.length()>13){
            offset+=102;
        }
        textBeans.add(textParameter("会议日期：2018/5/7-2018/5/10", false, 0,70, offset, Color.BLACK,new Font(null,Font.PLAIN,54)));
        offset+=102;
        textBeans.add(textParameter("会议场地：2楼国际会议厅", false, 0,70, offset, Color.BLACK,new Font(null,Font.PLAIN,54)));
        postMake(bg, textBeans, imgBeans, dir+"output.jpg");
    }

    /**
     * 返回/poster/xxx.jpg
     * @param poster
     * @return
     */
    public static String genPost(ActivityPoster poster){
        String bg = Global.getProjectPath()+"/xiu/poster_bg.jpg";
        if(!new File(Global.getProjectPath()+Global.getPosterPath()).exists()){
            new File(Global.getProjectPath()+Global.getPosterPath()).mkdirs();
        }
        String name=MD5.encodeString(poster.getTitle()+poster.getQrcodeUrl())+".jpg";
        String qrcode=MD5.encodeString(poster.getTitle()+poster.getQrcodeUrl())+"_qr.jpg";
        String qrPath=Global.getProjectPath()+Global.getPosterPath()+qrcode;
        QrUtil.genFile(poster.getQrcodeUrl(),qrPath);
        String output=Global.getProjectPath()+Global.getPosterPath()+name;

        List<ImgBean> imgBeans = new ArrayList<>();
        List<TextBean> textBeans = new ArrayList<>();
        int offset=0;
        imgBeans.add(imgParameter(imgLoadUrl(poster.getPoster()), false, 0, offset, 1080, 750));
        imgBeans.add(imgParameter(imgLoadUrl(qrPath), false, 720, 1530, 300, 300));
        offset=900;
        textBeans.add(textParameter(poster.getTitle(), false, 1.0f,70, offset, Color.BLACK,new Font(null,Font.BOLD,72)));
        offset+=200;
        if(poster.getTitle().length()>13){
            offset+=102;
        }
        textBeans.add(textParameter("会议日期："+poster.getTime(), false, 0,70, offset, Color.BLACK,new Font(null,Font.PLAIN,54)));
        offset+=102;
        textBeans.add(textParameter("会议场地："+poster.getAddr(), false, 0,70, offset, Color.BLACK,new Font(null,Font.PLAIN,54)));
        postMake(bg, textBeans, imgBeans, output);
        return Global.getPosterPath()+name;
    }

    public static void postMake(String bgPath, List<TextBean> textBeans, List<ImgBean> imgBeans, String output) {
        try {
            BufferedImage bgImg = imgLoadUrl(bgPath);
            ImageIO.write(createImg(bgImg, textBeans, imgBeans), "jpg", new File(output));
        } catch (IOException e) {
            log.error("error main", e);
        }
    }


    private static BufferedImage createImg(BufferedImage bgImg, List<TextBean> textBeans, List<ImgBean> imgBeans) {
        Graphics2D g = bgImg.createGraphics();
        //去锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //图片叠加
        imgSuperposition(g, bgImg.getWidth(), imgBeans);
        //添加文字
        textAddImg(g, bgImg.getWidth(), textBeans);
        g.dispose();
        return bgImg;

    }

    /**
     * 图片叠加
     *
     * @param g
     * @param imgBeans
     * @return 2017年3月12日
     * jianhui
     */
    private static Graphics2D imgSuperposition(Graphics2D g, Integer bgImgWidth, List<ImgBean> imgBeans) {
        try {
            for (int i = 0; i < imgBeans.size(); i++) {
                ImgBean imgBean = imgBeans.get(i);
                if (imgBean.isCenter()) { //是否居中判断
                    int x = (bgImgWidth - imgBean.getW()) / 2;
                    g.drawImage(imgBeans.get(i).getImg(), x, imgBean.getY(), imgBean.getW(), imgBean.getH(), null);
                } else {
                    g.drawImage(imgBeans.get(i).getImg(), imgBean.getX(), imgBean.getY(), imgBean.getW(), imgBean.getH(), null);
                }
            }
        } catch (Exception e) {
            log.error("error imgSuperposition", e);
        }
        return g;
    }

    /**
     * 添加文字
     *
     * @param g
     * @param bgImgWidth
     * @param textBeans
     * @return 2017年3月12日
     * jianhui
     */
    private static Graphics2D textAddImg(Graphics2D g, Integer bgImgWidth, List<TextBean> textBeans) {
        try {
            for (int i = 0; i < textBeans.size(); i++) {
                TextBean textBean = textBeans.get(i);
                g.setColor(textBean.getColor());
                g.setFont(textBean.getFont());
                int x = g.getFontMetrics().stringWidth(textBean.getName());
                ArrayList<String>titles=new ArrayList<>();
                if(x>940){
                    titles.add(textBean.getName().substring(0, 13));
                    titles.add(textBean.getName().substring(13));
                }else{
                    titles.add(textBean.getName());
                }
//                System.out.println("width:"+x);
                int offset=0;
                for(int index=0;index<titles.size();index++){
                    offset=index*102;
                    String title=titles.get(index);
                    int y=offset+textBean.getY();
                    if (textBean.isCenter()) {
                        if(textBean.getTextSpace()!=0){
                            drawString(title,(bgImgWidth - x) / 2,y,textBean.getTextSpace(),g);
                        }else{
                            g.drawString(title, (bgImgWidth - x) / 2, y);
                        }
                    } else {
                        if(textBean.getTextSpace()>0){
                            drawString(title, textBean.getX(), y, textBean.getTextSpace(), g);
                        }else{
                            g.drawString(title, textBean.getX(), y);
                        }
                    }
                }

            }
        } catch (Exception e) {
            System.out.println(e);
            log.error("error textAddImg", e);
        }

        return g;
    }

    private static void drawString(String str,int x,int y,double rate,Graphics2D g){
        String tempStr=new String();
        int orgStringWight=g.getFontMetrics().stringWidth(str);
        int orgStringLength=str.length();
        int tempx=x;
        int tempy=y;
        while(str.length()>0)
        {
            tempStr=str.substring(0, 1);
            str=str.substring(1, str.length());
            g.drawString(tempStr, tempx, tempy);
            tempx=(int)(tempx+(double)orgStringWight/(double)orgStringLength*rate);
        }
    }
//    /**
//     * 图片圆形处理  返回处理后的图片
//     *
//     * @param img           图片
//     * @param width         宽
//     * @param height        高
//     * @param rotationAngle 弧度
//     * @param margin        边距 不传则不设置背景
//     * @return
//     * @throws Exception 2017年3月12日
//     *                   jianhui
//     */
//    public static BufferedImage getCircularImg(BufferedImage img, Integer width, Integer height, Integer rotationAngle, Integer margin, Color color) {
//        BufferedImage circularImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//        Graphics2D g2 = circularImg.createGraphics();
//        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        g2.setColor(Color.WHITE);
//        g2.fill(new RoundRectangle2D.Float(0, 0, width, height, rotationAngle, rotationAngle));
//        g2.setComposite(AlphaComposite.SrcAtop);
//        g2.drawImage(img, 0, 0, width, height, null);
//        g2.dispose();
//        if (margin != null) {
//            circularImg = getCircularImgByBorder(circularImg, margin, color);
//        }
//        return circularImg;
//    }


//    /**
//     * 圆形图片添加圆形背景
//     *
//     * @param circularImg 传入的图
//     * @param margin      边距
//     * @param color       背景颜色
//     * @return
//     * @throws Exception 2017年3月12日
//     *                   jianhui
//     */
//    public static BufferedImage getCircularImgByBorder(BufferedImage circularImg, Integer margin, Color color) {
//        BufferedImage circularImgByBorder = new BufferedImage(circularImg.getWidth() + margin, circularImg.getHeight() + margin, circularImg.getType());
//        Graphics2D g = circularImgByBorder.createGraphics();
////去锯齿
//        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        g.setColor(color == null ? Color.WHITE : color);
//        g.fill(new RoundRectangle2D.Float(0, 0, circularImg.getWidth() + margin, circularImg.getHeight() + margin, ROTATION_ANGLE, ROTATION_ANGLE));
//        g.setComposite(AlphaComposite.SrcAtop);
//        g.drawImage(circularImg, margin / 2, margin / 2, circularImg.getWidth(), circularImg.getHeight(), null);
//        g.dispose();
//        return circularImgByBorder;
//    }

    /**
     * 获取图片
     *
     * @param imgUrl 图片路径
     * @return 2017年3月12日
     * jianhui
     */
    private static BufferedImage imgLoadUrl(String imgUrl) {
        try {
            if (imgUrl.startsWith("http://")) {
                return ImageIO.read(new URL(imgUrl));
            } else {
                return ImageIO.read(new File(imgUrl));
            }
        } catch (Exception e) {
            log.error("error imgLoadUrl", e);
        }
        return null;
    }

    /**
     * 图片设置参数
     *
     * @param img    图片
     * @param center 是否居中
     * @param x      如果居中 此值可以不用传
     * @param y      图片y轴初始位置
     * @param w      图片宽
     * @param h      图片高
     * @return 2017年3月12日
     * jianhui
     */
    private static ImgBean imgParameter(BufferedImage img, boolean center, Integer x, Integer y, Integer w, Integer h) {
        try {
            ImgBean imgBean = new ImgBean();
            imgBean.setImg(img);
            imgBean.setCenter(center);
            imgBean.setX(x == null ? 0 : x);
            imgBean.setY(y == null ? 0 : y);
            imgBean.setW(w == null ? img.getWidth() : w);
            imgBean.setH(h == null ? img.getHeight() : h);
            return imgBean;
        } catch (Exception e) {
            log.error("error imgParameter", e);
        }
        return null;

    }

    /**
     * 文字设置参数
     *
     * @param name   传入文字
     * @param center 是否居中
     * @param x      x轴位置
     * @param y      y轴位置
     * @param color  颜色
     * @param font   画笔
     * @return 2017年3月12日
     * jianhui
     */
    private static TextBean textParameter(String name, boolean center,float textSpace, Integer x, Integer y, Color color, Font font) {
        try {
            TextBean textBean = new TextBean();
            textBean.setName(name);
            textBean.setCenter(center);
            textBean.setX(x == null ? 0 : x);
            textBean.setY(y == null ? 0 : y);
            textBean.setColor(color == null ? Color.WHITE : color);
            textBean.setTextSpace(textSpace);
            textBean.setFont(font == null ? new Font("微软雅黑", Font.PLAIN, 30) : font);
            return textBean;
        } catch (Exception e) {
            log.error("error textParameter", e);
        }
        return null;
    }

    /**
     * 图片设置类
     * title imgParameter
     *
     * @author jianhui
     * @date 2017年3月12日
     */
    public static class ImgBean {
        /**
         * 图片buffer
         */
        private BufferedImage img;
        /**
         * 图片x轴标
         */
        private int x;
        /**
         * 图片y轴坐标
         */
        private int y;
        /**
         * 图片宽
         */
        private int w;
        /**
         * 图片高
         */
        private int h;
        /**
         * 图片是否居中
         */
        private boolean center;

        public BufferedImage getImg() {
            return img;
        }

        public void setImg(BufferedImage img) {
            this.img = img;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        public int getW() {
            return w;
        }

        public void setW(int w) {
            this.w = w;
        }

        public int getH() {
            return h;
        }

        public void setH(int h) {
            this.h = h;
        }

        public boolean isCenter() {
            return center;
        }

        public void setCenter(boolean center) {
            this.center = center;
        }

    }

    /**
     * 文字bean
     * title TextBean
     *
     * @author jianhui
     * @date 2017年3月12日
     */
    public static class TextBean {
        /**
         * 输入的文字
         */
        private String name;
        /**
         * 文字是否居中
         */
        private boolean center;
        /**
         * 文字的x轴位置
         */ //居中此值不用传
        private int x;
        /**
         * 文字的y轴位置
         */ //注：文字的位置计算是以文字的底部开始的，右下角，不像图片从左上角
        private int y;
        /**
         * 文字的颜色
         */
        private Color color;
        /**
         * 画笔
         */
        private Font font;

        private float textSpace;

        public float getTextSpace() {
            return textSpace;
        }

        public void setTextSpace(float textSpace) {
            this.textSpace = textSpace;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isCenter() {
            return center;
        }

        public void setCenter(boolean center) {
            this.center = center;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public Font getFont() {
            return font;
        }

        public void setFont(Font font) {
            this.font = font;
        }

    }


}